﻿using Microsoft.AspNetCore.SignalR;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Socket_Push_SDK
{
    internal static class LinkPool
    {
        static List<LinkInfo> linkInfos = new List<LinkInfo>();

        public static void Add(string id,string token, IClientProxy Client,HubCallerContext Context)
        {
            linkInfos.Add(new LinkInfo { ConnectionID = id, LinkID = token, Client = Client, Context = Context });
        }
        public static void RemovebyID(string id)
        {
            var linkInfo = linkInfos.FirstOrDefault(p => p.ConnectionID == id);
            if (linkInfo != null)
                linkInfos.Remove(linkInfo);
        }
        public static void RemovebyToken(string token)
        {
            var linkInfo = linkInfos.FirstOrDefault(p => p.LinkID == token);
            if (linkInfo != null)
                linkInfos.Remove(linkInfo);
        }
        public static IEnumerable<IClientProxy> FindClients()
        {
            return linkInfos.Select(p => p.Client);
        }
        public static IEnumerable<IClientProxy> FindClientbyID(string id)
        {
            return linkInfos.Where(p => p.ConnectionID == id).Select(p => p.Client);
        }
        public static IEnumerable<IClientProxy> FindClientbyToken(string token)
        {
            return linkInfos.Where(p => p.LinkID == token).Select(p => p.Client);
        }
        public static IEnumerable<HubCallerContext> FindContexts()
        {
            return linkInfos.Select(p => p.Context);
        }
        public static IEnumerable<HubCallerContext> FindContextbyID(string id)
        {
            return linkInfos.Where(p => p.ConnectionID == id).Select(p => p.Context);
        }
        public static IEnumerable<HubCallerContext> FindContextbyToken(string token)
        {
            return linkInfos.Where(p => p.LinkID == token).Select(p => p.Context);
        }
        public static List<LinkInfo> Find()
        {
            return linkInfos;
        }
        public static IEnumerable<LinkInfo> FindbyID(string id)
        {
            return linkInfos.Where(p => p.ConnectionID == id);
        }
        public static IEnumerable<LinkInfo> FindbyToken(string token)
        {
            return linkInfos.Where(p => p.LinkID == token);
        }
    }
    public class LinkInfo
    {
        /// <summary>
        /// 当前Socket连接ID
        /// </summary>
        public string ConnectionID { get; set; }
        /// <summary>
        /// 用户传入ID
        /// </summary>
        public string LinkID { get; set; }
        /// <summary>
        /// 当前连接的实体对象，可直接发送信息
        /// </summary>
        public IClientProxy Client { get; set; }
        /// <summary>
        /// 当前连接的请求，可直接发送信息
        /// </summary>
        public HubCallerContext Context { get; set; }
    }
}
